package com.xiaozhou.file;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.MapUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.collections4.CollectionUtils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
public class MainTest {


    private static Integer num = 2;

    private static Integer i = 98;

    private static String fileNamePath = "D://非重疾产品";
    private static String fileNamePath1 = "D://重疾产品";
    private static final String insertSql = "INSERT INTO t_rule_commission (created_by, created_dt,updated_by,updated_dt,deleted, version, rule_code, product_category_code, product_category_name, product_subcategory_code, product_subcategory_name, start_age_unit, end_age_unit, start_insured_age, end_insured_age, effective_start_date, effective_end_date, channel_code, year_1, year_2, year_3, year_4, year_5, year_6, year_7, year_8, year_9, year_10, year_11, year_12, year_13, year_14, year_15, year_16, year_17, year_18, year_19, year_20) VALUES ('sys', now(),'sys', now(), 0, 0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s , %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);";

    public static void main(String[] args) {
        Map<String, String> companyMap = JSONUtils.getCompanyMap();
        Map<String, String> productMap = JSONUtils.getProductMap();

        Map<String,List<ExcelDTO>> map = MapUtils.newHashMap();
        List<String> insertList = new ArrayList<>();

        ExcelUtils.getExcelList().forEach(excelDTO -> {
            if (Objects.isNull(companyMap.get(excelDTO.getCompanyCode())) || Objects.isNull(productMap.get(excelDTO.getProductCode()))){
                write("第："+num+"行产品编码或保司编码匹配不出来",".text");
//                write1("第："+num+"行产品编码或保司编码匹配不出来",".text");
                num++;
                return;
            }
            if (map.get(excelDTO.getCompanyCode()+excelDTO.getProductCode()) != null){
                Map<String, Object> ageMap = getAgeMap(excelDTO.getAgeStr());
                List<ExcelDTO> excelDTOS = map.get(excelDTO.getCompanyCode() + excelDTO.getProductCode());
                for (ExcelDTO dto : excelDTOS) {
                    Map<String, Object> ageMap1 = getAgeMap(dto.getAgeStr());
                    // 处理空值：起始时间为空视为负无穷，结束时间为空视为正无穷

                    // todo 修改年龄逻辑
                    Long starInsuredAge1 = getLongInsuredAge(ageMap1.get("startAge") == null ?  0 : Integer.parseInt(ageMap1.get("startAge").toString()),ageMap1.get("startUnit") == null ? null : ageMap1.get("startUnit").toString(),0);
                    Long starInsuredAge2 = getLongInsuredAge(ageMap.get("startAge") == null ?  0 : Integer.parseInt(ageMap.get("startAge").toString()),ageMap.get("startUnit") == null ? null : ageMap.get("startUnit").toString(),0);
                    Long endInsuredAge1 =  getLongInsuredAge(ageMap1.get("endAge") == null ?  0 : Integer.parseInt(ageMap1.get("endAge").toString()),ageMap1.get("endUnit") == null ? null : ageMap1.get("endUnit").toString(),360*200);
                    Long endInsuredAge2 = getLongInsuredAge(ageMap.get("endAge") == null ?  0 : Integer.parseInt(ageMap.get("endAge").toString()),ageMap.get("endUnit") == null ? null : ageMap.get("endUnit").toString(),360*200);
                    // 判断是否有冲突
                    if (!(endInsuredAge1 < starInsuredAge2 || endInsuredAge2 < starInsuredAge1) ){
                        System.out.println("有冲突：冲突数据为："+ JSONUtil.toJsonStr(excelDTO));
                        break;
                    }
                }
                map.get(excelDTO.getCompanyCode() + excelDTO.getProductCode()).add(excelDTO);
            }else {
                List<ExcelDTO> objects = new ArrayList<>();
                objects.add(excelDTO);
                map.put(excelDTO.getCompanyCode()+excelDTO.getProductCode(),objects);
            }

            String dateStr = excelDTO.getAgeStr();
            Map<String, Object> ageMap = getAgeMap(dateStr);
            String format = String.format(insertSql,
                    getStr(generateNext(i)),
                    getStr(excelDTO.getCompanyCode()),
                    getStr(companyMap.get(excelDTO.getCompanyCode())),
                    getStr(excelDTO.getProductCode()),
                    getStr(productMap.get(excelDTO.getProductCode())),
                    getStr(ageMap.get("startUnit")),
                    getStr(ageMap.get("endUnit")),
                    ageMap.get("startAge"),
                    ageMap.get("endAge"),
                    null,
                    null,
                    getStr("QD000002"),
                    getBigDecimal(excelDTO.getYear1Str()),
                    getBigDecimal(excelDTO.getYear2Str()),
                    getBigDecimal(excelDTO.getYear3Str()),
                    getBigDecimal(excelDTO.getYear4Str()),
                    getBigDecimal(excelDTO.getYear5Str()),
                    getBigDecimal(excelDTO.getYear6Str()),
                    getBigDecimal(excelDTO.getYear7Str()),
                    getBigDecimal(excelDTO.getYear8Str()),
                    getBigDecimal(excelDTO.getYear9Str()),
                    getBigDecimal(excelDTO.getYear10Str()),
                    getBigDecimal(excelDTO.getYear11Str()),
                    getBigDecimal(excelDTO.getYear12Str()),
                    getBigDecimal(excelDTO.getYear13Str()),
                    getBigDecimal(excelDTO.getYear14Str()),
                    getBigDecimal(excelDTO.getYear15Str()),
                    getBigDecimal(excelDTO.getYear16Str()),
                    getBigDecimal(excelDTO.getYear17Str()),
                    getBigDecimal(excelDTO.getYear18Str()),
                    getBigDecimal(excelDTO.getYear19Str()),
                    getBigDecimal(excelDTO.getYear20Str()));
                    insertList.add(format);
            write(format,".sql");
//            write1(format,".sql");
            i++;
            num++;
        });

        System.out.println(insertList);
    }

    private static Long getLongInsuredAge(Integer insureAge, String ageUnit,Integer day) {
        return  (insureAge != null ?
                Objects.equals("YEAR",ageUnit) ?
                        Math.multiplyExact((long) insureAge , 365l) :
                        insureAge : day);
    }

    private static void write(String format,String fileName) {
        try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileNamePath + fileName,  true))) {
            writer.write(format);
            writer.newLine();
            writer.newLine();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void write1(String format,String fileName) {
        try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileNamePath1 + fileName,  true))) {
            writer.write(format);
            writer.newLine();
            writer.newLine();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static String getStr(Object s){
        if (s == null){
            return null;
        }
        return "'"+s+"'";
    }

    public static String generateNext(Integer num) {
        return String.format("GZ%06d", num);
    }

    private static BigDecimal getBigDecimal(String s){
        try {
            if (s == null){
                return null;
            }
            String s1 = s.split("%")[0];
            return new BigDecimal(s1);
        }catch (Exception e){
            return null;
        }

    }

    private static Map<String,Object> getAgeMap(String ageDateStr){
        if (Objects.isNull(ageDateStr)){
            return MapUtils.newHashMap();
        }
        return parseAgeRange(ageDateStr);
    }

//    public static void main(String[] args) {
//        String[] ageStrings = { "1-65岁", "无年龄限制", "15天-60岁", "(<=65岁)", "(> 65岁)", "(> 65岁)" };
//        for (String ageStr : ageStrings) {
//            parseAgeRange(ageStr);
//        }
//    }

    public static Map<String,Object> parseAgeRange(String ageRange) {

        Map<String, Object> map = new HashMap<>();
        Integer startAge = null;
        Integer endAge = null;   // Initialize to maximum value to indicate no limit

        String startUnit = null;
        String endUnit = null;

        // Check if the string " is无年龄限制"
        if (ageRange.contains("无年龄限制")) {
            startUnit = null;
            endUnit = null;
        } else if (ageRange.contains("天")) {
            // Check if there's a '天' unit in the string
            Pattern patternDays = Pattern.compile("(\\d+)(天)\\s*\\-\\s*(\\d+)(岁|天)?");
            Matcher matcherDays = patternDays.matcher(ageRange);
            if (matcherDays.find()) {
                startAge = Integer.parseInt(matcherDays.group(1));
                startUnit = matcherDays.group(2);
                endAge = Integer.parseInt(matcherDays.group(3));
                endUnit = matcherDays.group(4) != null ? matcherDays.group(4) : "天"; // Default to '天' if unit not found
            }
        } else if (ageRange.contains("-")) {
            // Check for the standard age range format e.g., "1-65岁"
            Pattern patternStandard = Pattern.compile("(\\d+)\\-\\s*(\\d+)(岁|天)");
            Matcher matcherStandard = patternStandard.matcher(ageRange);
            if (matcherStandard.find()) {
                startAge = Integer.parseInt(matcherStandard.group(1));
                endAge =Integer.parseInt(matcherStandard.group(2));
                startUnit = matcherStandard.group(3);
                endUnit = matcherStandard.group(3);
            }
        } else if (ageRange.contains("<=")) {
            // Check for the format "(<=65岁)"
            Pattern patternLe = Pattern.compile("\\(<=\\s*(\\d+)(岁|天)\\)");
            Matcher matcherLe = patternLe.matcher(ageRange);
            if (matcherLe.find()) {
                endAge = Integer.parseInt(matcherLe.group(1));
                endUnit = matcherLe.group(2);
                startUnit = endUnit;
            }
        } else if (ageRange.contains(">")) {
            // Check for the format "(> 65岁)"
            Pattern patternGt = Pattern.compile("\\(>\\s*(\\d+)(岁|天)\\)");
            Matcher matcherGt = patternGt.matcher(ageRange);
            if (matcherGt.find()) {
                startAge = Integer.parseInt(matcherGt.group(1)) + 1; // Starting from the next value
                startUnit = matcherGt.group(2);
                endUnit = matcherGt.group(2);
            }
        }

        map.put("startAge", startAge);
        map.put("endAge", endAge);
        map.put("startUnit",startAge == null ? null : startUnit !=null ? Objects.equals(startUnit, "天") ? "DAY": "YEAR" : null);
        map.put("endUnit", endAge == null ? null : endUnit !=null ? Objects.equals(endUnit, "天") ? "DAY": "YEAR" : null);
        // Print the extracted values
//        System.out.println("Original String: " + ageRange);
//        System.out.println("StartAge: " + startAge);
//        System.out.println("EndAge: " + endAge);
//        System.out.println("StartUnit: " + (startAge == null ? null : startUnit !=null ? Objects.equals(startUnit, "天") ? "DAY": "YEAR" : null));
//        System.out.println("EndUnit: " + ( endAge == null ? null : endUnit !=null ? Objects.equals(endUnit, "天") ? "DAY": "YEAR" : null));
//        System.out.println("-----------------------------------");
        return map;
    }


}
